<template>
  <div class="container">
    <!-- 左右两栏布局 -->
    <div class="qweather-layout d-flex align-items-start justify-content-between" style="height:auto!important">
      <!-- 左侧列表 -->
      <div class="qweather-list" style="height:auto!important">
        <!-- 当前预警信息 -->
        <div v-if="currentWarning" class="qweather-list__row">
          <div :class="['c-city-warning-events', getWarningClass(currentWarning.severity)]">
            <div class="warning-events__top d-flex align-items-center">
              <div class="warning-events__icon">
                <i :class="getWarningIcon(currentWarning.typeName)"></i>
              </div>
              <div class="cont">
                <h3>{{ currentWarning.title }}</h3>
                <p>发布日期：{{ formatDate(currentWarning.pubTime) }}</p>
              </div>
            </div>
            <p class="warning-events__txt">{{ currentWarning.text }}</p>
            <div v-if="currentWarning.related" class="warning-explain">
              <h4>说明</h4>
              <p>{{ currentWarning.related }}</p>
            </div>
            <div v-if="currentWarning.defense" class="warning-defense--bg">
              <h4 class="warning-defense__title">防御指南</h4>
              <div class="warning-defense__txt" v-html="formatDefense(currentWarning.defense)"></div>
            </div>
          </div>
        </div>

        <!-- 无预警信息提示 -->
        <div v-else class="qweather-list__row">
          <div class="c-city-warning-events warning--none">
            <div class="warning-events__top d-flex align-items-center">
              <div class="warning-events__icon" style="background-color: #95B359;">
                <i class="qi-100"></i>
              </div>
              <div class="cont">
                <h3>当前无灾害预警</h3>
                <p>{{ currentLocation.city }}{{ currentLocation.district }}暂无气象灾害预警信息</p>
              </div>
            </div>
            <p class="warning-events__txt">请继续关注天气变化，注意日常防护。</p>
          </div>
        </div>

        <!-- 最新预警信息 -->
        <div class="qweather-list__row">
          <div class="c-city-warning-around">
            <h3 class="qweather-title">最新预警信息</h3>
            <div class="qweather-tabs">
              <a v-for="(warning, index) in latestWarnings" :key="index" href="#" class="tabs__row d-flex align-items-center">
                <div class="city">
                  <p>{{ warning.city }}</p>
                </div>
                <span :class="['warning-level', getWarningLevelClass(warning.severity)]">{{ getSeverityText(warning.severity) }}</span>
                <span class="warning-txt">{{ warning.typeName }}</span>
              </a>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧菜单 -->
      <div class="qweather-menu" style="height:auto!important">
        <!-- 占位内容 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import 'qweather-icons/font/qweather-icons.css'

// API配置
const API_KEY = '78db6a9c3b4d445881d8fa1ba2d0fa8a'
const API_BASE_URL = 'https://pr6yvxwd8j.re.qweatherapi.com'

// 当前位置
const currentLocation = ref({
  longitude: 114.40,
  latitude: 30.50,
  city: '武汉市',
  district: '洪山区',
  locationId: '101200106' // 武汉洪山区的location ID
})

// 当前预警数据
const currentWarning = ref(null)

// 最新预警信息列表
const latestWarnings = ref([
  { city: '赤城，河北省', severity: 'Minor', typeName: '大风' },
  { city: '离石，山西省', severity: 'Moderate', typeName: '地质灾害气象风险' },
  { city: '沽源，河北省', severity: 'Minor', typeName: '大风' },
  { city: '康保，河北省', severity: 'Moderate', typeName: '雷电' },
  { city: '兴山，湖北省', severity: 'Moderate', typeName: '强对流' },
  { city: '宣化，河北省', severity: 'Minor', typeName: '大风' },
  { city: '怀来，河北省', severity: 'Minor', typeName: '大风' },
  { city: '南海，广东省', severity: 'Moderate', typeName: '暴雨' },
  { city: '三元，福建省', severity: 'Moderate', typeName: '雷雨大风' },
  { city: '五台县，山西省', severity: 'Minor', typeName: '雷暴大风' }
])

// 获取当前位置
const getCurrentLocation = () => {
  return new Promise((resolve, reject) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        async (position) => {
          currentLocation.value.latitude = position.coords.latitude
          currentLocation.value.longitude = position.coords.longitude

          // 获取城市信息和location ID
          await getCityInfo(position.coords.longitude, position.coords.latitude)
          resolve()
        },
        (error) => {
          console.error('获取位置失败:', error)
          // 使用默认位置
          resolve()
        },
        {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 0
        }
      )
    } else {
      console.log('浏览器不支持地理定位')
      resolve()
    }
  })
}

// 获取城市信息
const getCityInfo = async (longitude, latitude) => {
  try {
    // 使用GeoAPI获取城市信息
    const response = await axios.get(
      `${API_BASE_URL}/geo/v2/city/lookup`,
      {
        params: {
          location: `${longitude.toFixed(2)},${latitude.toFixed(2)}`,
          key: API_KEY,
          lang: 'zh'
        }
      }
    )

    if (response.data && response.data.code === '200' && response.data.location) {
      const location = response.data.location[0]
      currentLocation.value.city = location.adm2 || location.name
      currentLocation.value.district = location.name
      currentLocation.value.locationId = location.id
    }
  } catch (error) {
    console.error('获取城市信息失败，使用坐标作为位置:', error)
    // 如果获取失败，直接使用坐标作为location参数
    currentLocation.value.locationId = `${longitude.toFixed(2)},${latitude.toFixed(2)}`
  }
}

// 获取灾害预警数据
const fetchWarningData = async () => {
  try {
    // 使用坐标或locationId作为位置参数
    const locationParam = currentLocation.value.locationId ||
                         `${currentLocation.value.longitude.toFixed(2)},${currentLocation.value.latitude.toFixed(2)}`

    const response = await axios.get(
      `${API_BASE_URL}/v7/warning/now`,
      {
        params: {
          location: locationParam,
          key: API_KEY,
          lang: 'zh'
        }
      }
    )

    if (response.data && response.data.code === '200') {
      if (response.data.warning && response.data.warning.length > 0) {
        // 有预警信息，取第一条作为当前预警
        const warning = response.data.warning[0]
        currentWarning.value = {
          ...warning,
          defense: parseDefenseText(warning.text)
        }
      } else {
        // 无预警信息
        currentWarning.value = null
      }
    }
  } catch (error) {
    console.error('获取灾害预警数据失败:', error)
    // 使用模拟数据
    currentWarning.value = {
      title: '武汉市气象台发布高温黄色预警',
      pubTime: '2025-09-15T09:07+08:00',
      text: '武汉市气象台2025年09月15日09时07分发布高温黄色预警信号：预计今天白天，中心城区、东湖高新、蔡甸、经开、江夏部分街道（乡镇）最高气温将升至35℃以上，请注意防范。',
      typeName: '高温',
      severity: 'Moderate',
      related: '连续三天日最高气温将在35°C以上。',
      defense: '1、有关部门和单位按照职责做好防暑降温准备工作；\n2、午后尽量减少户外活动；\n3、对老、弱、病、幼人群提供防暑降温指导；\n4、高温条件下作业和白天需要长时间进行户外露天作业的人员应当采取必要的防护措施。'
    }
  }
}

// 获取其他地区预警信息（用于最新预警列表）
const fetchOtherWarnings = async () => {
  try {
    // 先获取有预警的城市列表
    const listResponse = await axios.get(
      `${API_BASE_URL}/v7/warning/list`,
      {
        params: {
          range: 'cn',
          key: API_KEY
        }
      }
    )

    if (listResponse.data && listResponse.data.code === '200' && listResponse.data.warningLocList) {
      const locationIds = listResponse.data.warningLocList.map(item => item.locationId)

      // 随机选取10个城市获取详细预警信息
      const selectedIds = locationIds.slice(0, 10)
      const warningPromises = selectedIds.map(async (locationId) => {
        try {
          const response = await axios.get(
            `${API_BASE_URL}/v7/warning/now`,
            {
              params: {
                location: locationId,
                key: API_KEY,
                lang: 'zh'
              }
            }
          )

          if (response.data && response.data.code === '200' && response.data.warning && response.data.warning.length > 0) {
            const warning = response.data.warning[0]
            // 从预警信息中提取城市名称
            let cityName = '未知城市'
            if (warning.sender) {
              // 从发布机构名称中提取城市信息
              // 例如："北京市气象台" -> "北京市"
              const match = warning.sender.match(/(.*?)[市县区]/)
              if (match) {
                cityName = match[0]
              }
            }

            return {
              city: cityName,
              severity: warning.severity || 'Moderate',
              typeName: warning.typeName || '预警'
            }
          }
        } catch (error) {
          console.error('获取单个城市预警失败:', error)
        }
        return null
      })

      const results = await Promise.all(warningPromises)
      const validWarnings = results.filter(w => w !== null)

      if (validWarnings.length > 0) {
        latestWarnings.value = validWarnings
      }
    }
  } catch (error) {
    console.error('获取城市预警列表失败:', error)
    // 使用默认数据
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return dateStr.replace('T', ' ').replace('+08:00', '')
}

// 解析防御指南文本
const parseDefenseText = (text) => {
  if (!text) return ''
  // 尝试从文本中提取防御指南部分
  const defenseMatch = text.match(/防御指南[：:]([\s\S]*)/i)
  if (defenseMatch) {
    return defenseMatch[1].trim()
  }
  return ''
}

// 格式化防御指南
const formatDefense = (defense) => {
  if (!defense) return ''
  // 将换行符转换为段落
  return defense.split('\n').map(line => `<p>${line}</p>`).join('')
}

// 获取预警等级样式类
const getWarningClass = (severity) => {
  const severityMap = {
    'Minor': 'warning--blue',
    'Moderate': 'warning--yellow',
    'Severe': 'warning--orange',
    'Extreme': 'warning--red'
  }
  return severityMap[severity] || 'warning--yellow'
}

// 获取预警图标
const getWarningIcon = (typeName) => {
  const iconMap = {
    '高温': 'qi-1009',
    '大风': 'qi-1006',
    '暴雨': 'qi-1007',
    '雷电': 'qi-1005',
    '雷雨': 'qi-1005',
    '大雾': 'qi-501',
    '暴雪': 'qi-1008',
    '寒潮': 'qi-1025',
    '台风': 'qi-1010',
    '冰雹': 'qi-1012',
    '道路结冰': 'qi-1027',
    '地质灾害': 'qi-1015'
  }

  // 查找匹配的图标
  for (const [key, value] of Object.entries(iconMap)) {
    if (typeName && typeName.includes(key)) {
      return value
    }
  }
  return 'qi-999' // 默认预警图标
}

// 获取预警等级样式
const getWarningLevelClass = (severity) => {
  const severityMap = {
    'Minor': 'warning-level--blue',
    'Moderate': 'warning-level--yellow',
    'Severe': 'warning-level--orange',
    'Extreme': 'warning-level--red'
  }
  return severityMap[severity] || 'warning-level--yellow'
}

// 获取预警等级文本
const getSeverityText = (severity) => {
  const severityMap = {
    'Minor': '蓝',
    'Moderate': '黄',
    'Severe': '橙',
    'Extreme': '红'
  }
  return severityMap[severity] || '黄'
}

// 在组件挂载后获取数据
onMounted(async () => {
  // 先获取当前位置
  await getCurrentLocation()
  // 然后获取预警数据
  await fetchWarningData()
  // 获取其他地区预警
  await fetchOtherWarnings()
})
</script>

<style scoped>
/* 容器样式 */
.container {
  max-width: 1200px;
  padding-left: 20px;
  padding-right: 20px;
  margin: 0 auto;
}

/* 左右布局 */
.qweather-layout {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.qweather-list {
  flex: 1 0 auto;
  width: 0;
}

.qweather-list .qweather-list__row {
  margin: 0 0 20px;
  background: none;
  border: none;
  padding: 0;
}

.qweather-list .qweather-list__row:last-child {
  margin: 0;
}

.qweather-menu {
  flex: 0 0 300px;
  width: 0;
  max-width: 300px;
  margin-left: 20px;
}

.justify-content-between {
  justify-content: space-between !important;
}

.c-city-warning-events {
  border-radius: 16px;
  padding: 30px 20px 20px;
}

.c-city-warning-events .warning-events__top .warning-events__icon {
  flex: 0 0 80px;
  width: 0;
  height: 80px;
  text-align: center;
  border-radius: 10px;
  margin-right: 20px;
  box-sizing: border-box;
  padding: 10px 0;
}


.c-city-warning-events .warning-events__top .cont > h3 {
  font-size: 18px;
  line-height: 1.5;
  color: var(--text-black-1);
}

.c-city-warning-events .warning-events__top .cont > p {
  margin-top: 7px;
  font-size: 12px;
  line-height: 1.5;
  color: var(--text-black-2);
}

.c-city-warning-events .warning-events__txt {
  margin: 16px 0 0;
  font-size: 15px;
  line-height: 1.5;
  color: var(--text-black-1);
}

.c-city-warning-events .warning-explain {
  margin-top: 24px;
  border-radius: 15px;
  padding: 14px 16px;
  background-color: var(--city--warning-events-defense-background-color);
}

.c-city-warning-events .warning-explain > h4 {
  font-size: 15px;
  line-height: 16px;
  color: var(--text-black-1);
}

.c-city-warning-events .warning-explain > p {
  margin-top: 10px;
  font-size: 15px;
  line-height: 1.5;
  color: var(--text-black-2);
}

.c-city-warning-events .warning-defense--bg {
  margin-top: 10px;
  border-radius: 15px;
  padding: 14px 16px;
  background-color: var(--city--warning-events-defense-background-color);
}

.c-city-warning-events .warning-defense__title {
  font-size: 15px;
  line-height: 16px;
  color: var(--text-black-1);
}

.c-city-warning-events .warning-defense__txt {
  margin-top: 10px;
  font-size: 15px;
  line-height: 1.5;
  color: var(--text-black-2);
}

.c-city-warning-events .warning-defense__txt > p {
  font-size: inherit;
  font-weight: inherit;
  line-height: inherit;
  color: inherit;
}

/* 预警等级颜色 */
.warning--none {
  background-color: #F0F9FF;
}

.warning--blue {
  background-color: #E6F4FF;
}

.warning--blue .warning-events__icon {
  background-color: #41a0f8;
}

.warning--yellow {
  background-color: #FFFEEE;
}

.warning--yellow .warning-events__icon {
  background-color: #FFD700;
}

.warning--orange {
  background-color: #FFF4E6;
}

.warning--orange .warning-events__icon {
  background-color: #f8a931;
}

.warning--red {
  background-color: #FFE6E6;
}

.warning--red .warning-events__icon {
  background-color: #FF4444;
}

.d-flex {
  display: -ms-flexbox !important;
  display: flex !important;
}

.align-items-center {
  -ms-flex-align: center !important;
  align-items: center !important;
}

/* CSS变量定义 */
:root {
  --text-black-1: rgba(0, 0, 0, 1);
  --text-black-2: rgba(0, 0, 0, 0.5);
  --city--warning-events-defense-background-color: #F2F3F5;
  --card-background-color: #F7F8F9;
  --card-border-color: #F2F4FA;
  --tabs-row-background-color: rgba(0, 0, 0, 0.03);
}

/* 最新预警信息样式 */
.c-city-warning-around {
  border-radius: 16px;
  background-color: var(--card-background-color);
  border: 1px solid var(--card-border-color);
  padding: 30px 20px 20px;
}

.c-city-warning-around > .qweather-tabs {
  margin-top: 28px;
}

.c-city-warning-around > .qweather-tabs .tabs__row .city {
  flex: 1 0 auto;
  width: 0;
}

.c-city-warning-around > .qweather-tabs .tabs__row .warning-txt {
  flex: 0 0 200px;
  width: 0;
  text-align: right;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.qweather-title {
  font-size: 20px;
  font-weight: 500;
  line-height: 22px;
  color: var(--text-black-1);
  text-align: center;
}

.qweather-tabs .tabs__row {
  border-radius: 11px;
  background-color: var(--tabs-row-background-color);
  padding: 0 16px;
  height: 40px;
  margin-bottom: 6px;
  text-decoration: none;
  display: flex;
}

.qweather-tabs .tabs__row > .city > p {
  font-size: 16px;
  line-height: 1.5;
  color: var(--text-black-1);
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin: 0;
}

.qweather-tabs .tabs__row > span {
  font-size: 18px;
  font-weight: 500;
  color: var(--text-black-1);
}

.qweather-tabs .tabs__row > span.warning-level {
  flex: 0 0 65px;
  width: 0;
  margin: 0 8px;
  font-size: 16px;
  font-weight: normal;
  line-height: 24px;
  text-align: center;
  color: var(--text-black-1);
}

.qweather-tabs .tabs__row:last-child {
  margin: 0;
}

.warning-level {
  border-radius: 14px;
}

.warning-level--red {
  color: white !important;
  background-color: #FF4444;
}

.warning-level--orange {
  color: white !important;
  background-color: #f8a931;
}

.warning-level--yellow {
  color: white !important;
  background-color: #b1ae48;
}

.warning-level--blue {
  color: white !important;
  background-color: #41a0f8;
}

/* 预警图标样式 */
.c-city-warning-events .warning-events__icon > i {
  display: block;
  width: 60px;
  height: 60px;
  font-size: 60px;
  line-height: 60px;
  color: #FAFAFA;
  font-style: normal;
  outline: none;
  margin: 0 auto;
}

.c-city-warning-events .warning-events__icon > i::before {
  vertical-align: 0;
}

@media (max-width: 879px) and (min-width: 740px) {
  .c-city-warning-around {
    padding: 30px 16px 20px;
  }

  .c-city-warning-around > .qweather-tabs .tabs__row .warning-level {
    flex: 0 0 60px;
    font-size: 14px;
  }

  .c-city-warning-around > .qweather-tabs .tabs__row .warning-txt {
    flex: 0 0 90px;
    font-size: 16px;
  }
}

@media (max-width: 739px) {
  .container {
    padding-left: 16px;
    padding-right: 16px;
  }

  .qweather-layout {
    flex-direction: column !important;
    justify-content: center !important;
    align-items: stretch !important;
  }

  .qweather-layout .qweather-list {
    flex: 1 0 100%;
    width: 100%;
    max-width: 100%;
  }

  .qweather-layout .qweather-list .qweather-list__row {
    margin: 0 0 12px;
  }

  .qweather-layout .qweather-menu {
    flex: 1 0 100%;
    width: 100%;
    max-width: 100%;
    margin: 12px 0 0;
  }

  .c-city-warning-events {
    padding: 30px 16px 20px;
  }

  .c-city-warning-events .warning-events__txt {
    margin: 24px 0 0;
  }

  .c-city-warning-events .warning-explain > h4 {
    font-size: 14px;
  }

  .c-city-warning-events .warning-explain > p {
    font-size: 14px;
  }

  .c-city-warning-events .warning-defense__title {
    font-size: 14px;
  }

  .c-city-warning-events .warning-defense__txt {
    font-size: 14px;
  }

  .qweather-tabs .tabs__row > span.warning-level {
    font-size: 14px;
  }
}

@media (max-width: 512px) {
  .c-city-warning-around {
    padding: 30px 16px 20px;
  }

  .c-city-warning-around > .qweather-tabs .tabs__row .warning-level {
    flex: 0 0 60px;
  }

  .c-city-warning-around > .qweather-tabs .tabs__row .warning-txt {
    flex: 0 0 90px;
    font-size: 16px;
  }
}
</style>

